package com.liu.designmode.completeable;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;
import java.util.function.Supplier;

public class ThreadUtil {


    static class UserThreadPoolInstance {

        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("user-worker-thread-%d")
                .setDaemon(false)
                .build();

        int cpuCount = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(cpuCount, cpuCount * 2, 3, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(100),
                 threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy());


        public static final UserThreadPoolInstance INSTANCE = new UserThreadPoolInstance();

        public static UserThreadPoolInstance getInstance() {
            return INSTANCE;
        }

        public CompletableFuture<Void> runSync(Runnable task) {
            return CompletableFuture.runAsync(task, executor);
        }

        public <T> CompletableFuture<T> supplySync(Supplier<T> supplier) {
            return CompletableFuture.supplyAsync(supplier::get, executor);
        }
    }
}
